package service

import (
	"context"
	"github.com/spf13/viper"
	"go-shop-admin/internal/dao"
	"go-shop-admin/internal/model"
	"go-shop-admin/pkg/e"
	"go-shop-admin/pkg/funs"
	"go-shop-admin/pkg/serializer"
	"go-shop-admin/pkg/zydhlog"
)

// AuthService api接口暴露的字段等
type AuthService struct {
	Account  string `form:"account" json:"account" binding:"required,alphanum"  _:"comment:登录账号"`
	Username string `form:"username" json:"username" binding:"required" _:"comment:用户名"`
	Password string `form:"password" json:"password"  binding:"required,alphanum" _:"comment:密码 sha1加密"` // checkPsw  0x7C== |  0x2c == ,  0x2e == .  0x2d == -  0x5f == _
	//当搜索条件与特殊标记冲突时,如：逗号（,），或操作（|），中横线（-）等则需要使用 UTF-8十六进制表示形式  `validate:"excludesall=|"`    // 错误   `validate:"excludesall=0x7C"` // 正确.
	RePassword string `form:"re_password"  json:"re_password" binding:"required,eqfield=Password" _:"comment:密码 sha1加密"`
	Desc       string `form:"desc" json:"desc" `
	Phone      string `form:"phone" json:"phone" binding:"required,checkPhone"`
	Email      string `form:"email" json:"email"  binding:"required,email"`
	Avatar     string `form:"avatar" json:"avatar"`
	RoleId     uint   `form:"role_id" json:"role_id" binding:"required,numeric" _:"comment:角色表auth_role主键id"`
	LoginNum   uint   `form:"login_num" json:"login_num"`
	Sort       uint   `form:"sort" json:"sort"`
	Status     uint   `form:"status" json:"status"`
	//LastLoginIp   string    `form:"last_login_ip" json:"last_login_ip"`
	//LastLoginTime time.Time `form:"last_login_time" json:"last_login_time" `
	//ThisLoginIp   string    `form:"this_login_ip" json:"this_login_ip" `
	//ThisLoginTime time.Time `form:"this_login_time" json:"this_login_time"`
}

// Show 显示
func (s *AuthService) Show(ctx context.Context, id uint) *serializer.Response {
	authDao := dao.NewAuthDao(ctx)
	auth, err := authDao.GetById(id)
	if err != nil {
		zydhlog.Error(err.Error())
		return serializer.NewResponse(e.ErrorExistAuthNotFind, err.Error(), e.TipsGeneral, nil)
	}
	//返回信息
	return serializer.NewResponse(e.Success, e.TipsOk, e.TipsSuccessOperate, serializer.BuildAuth(auth))
}

// Create 创建
func (s *AuthService) Create(ctx context.Context) *serializer.Response {
	//把传递过来的pwd解码，然后再校验密码
	authDao := dao.NewAuthDao(ctx)
	//通过账号或者手机号查找用户

	whereMap := dao.WhereStruct{
		Where: map[string]interface{}{
			"account": s.Account,
		},
		OrWhere: map[string]interface{}{
			"phone": s.Phone,
			"email": s.Email,
		},
	}

	_, ok, err := authDao.ExistOrNotByWhere(whereMap)
	if err != nil {
		return serializer.NewResponse(e.Error, err.Error(), e.TipsGeneral, nil)
	}
	//存在
	if ok {
		return serializer.NewResponse(e.ErrorExistAuth, e.TipsNil, e.TipsErrorExistUser, nil)
	}

	//密码加密
	password, err := funs.BcryptPwd(s.Password, 12)
	if err != nil {
		zydhlog.Error(err.Error())
		return serializer.NewResponse(e.ErrorFailEncrypt, err.Error(), e.TipsGeneral, nil)
	}

	//不存在，创建
	authCreate := &model.Auth{
		Account:  s.Account,
		Username: s.Username,
		Password: password,
		Desc:     s.Desc,
		Phone:    funs.AesEncoding(funs.CutStrNumByScene(s.Account, 6, 2), s.Phone), //ase 加密
		Email:    funs.AesEncoding(funs.CutStrNumByScene(s.Account, 6, 1), s.Email), //ase 加密
		Avatar:   viper.GetString("path.default_avatar_path"),                       //使用默认头像,
		RoleId:   s.RoleId,
	}

	if err = authDao.AuthCreate(authCreate); err != nil {
		zydhlog.Error(err.Error())
		return serializer.NewResponse(e.Error, err.Error(), e.TipsGeneral, nil)
	}

	return serializer.NewResponse(e.Success, e.TipsOk, e.TipsSuccessCreateAuth, nil)
}

// Update 修改
func (s *AuthService) Update(ctx context.Context, id uint) *serializer.Response {
	authDao := dao.NewAuthDao(ctx)
	//通过id判断用户是否存在
	auth, err := authDao.GetById(id)
	if err != nil {
		zydhlog.Error(err.Error())
		return serializer.NewResponse(e.ErrorExistAuthNotFind, err.Error(), e.TipsGeneral, nil)
	}
	authUpdate := &model.Auth{
		Account:  s.Account,
		Username: s.Username,
		Desc:     s.Desc,
		Phone:    funs.AesEncoding(funs.CutStrNumByScene(s.Account, 6, 2), s.Phone), //ase 加密
		Email:    funs.AesEncoding(funs.CutStrNumByScene(s.Account, 6, 1), s.Email), //ase 加密
		Avatar:   s.Avatar,
		RoleId:   s.RoleId,
		BaseModel: model.BaseModel{
			Status: s.Status,
			Sort:   s.Sort,
		},
	}

	//判断密码是否需要修改

	//密码加密
	password, err := funs.BcryptPwd(s.Password, 12)
	if err != nil {
		zydhlog.Error(err.Error())
		return serializer.NewResponse(e.ErrorFailEncrypt, err.Error(), e.TipsGeneral, nil)
	}

	if password != auth.Password {
		authUpdate.Password = password
	}

	//更新用户
	if err = authDao.AuthUpdate(id, authUpdate); err != nil {
		zydhlog.Error(err.Error())
		return serializer.NewResponse(e.Error, err.Error(), e.TipsGeneral, nil)
	}

	return serializer.NewResponse(e.Success, e.TipsOk, e.TipSuccessUpdate, nil)
}

// Delete 删除
func (s *AuthService) Delete(ctx context.Context, ids []string) *serializer.Response {
	authDao := dao.NewAuthDao(ctx)
	if err := authDao.Delete(ids); err != nil {
		zydhlog.Error(err.Error())
		return serializer.NewResponse(e.Error, err.Error(), e.TipsGeneral, nil)
	}
	return serializer.NewResponse(e.Success, e.TipsOk, e.TipSuccessDelete, nil)
}
